
//
//  ZZOrderVC.m
//  新项目
//
//  Created by 刘耀宗 on 2016/12/19.
//  Copyright © 2016年 刘耀宗. All rights reserved.
//

#import "ZZOrderVC.h"
#import "ZZOrderHeaderView.h"
#import "ZZOrderHeaderViewCell.h"
#import "WBPopMenuModel.h"
#import "WBPopMenuSingleton.h"
#import "ZZTimeModel.h"
#import "ZZOrderViewModel.h"
#import "ZZSettingVC.h"
#import "ZZOrderModel.h"
#import "ZZOrderContentModel.h"
#import "ZZOrderPopView.h"
@interface ZZOrderVC ()<UITableViewDelegate,UITableViewDataSource,ZZOrderPopViewDelegate>
@property (nonatomic,strong) ZZOrderHeaderView *header;
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *mutaArr;
@property (nonatomic, assign) NSInteger total;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) NSInteger num;
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (nonatomic,strong)NSString *currentMonthStr;
@property (nonatomic, strong) CcNoDataView *noDataView;

@property(nonatomic,strong)ZZOrderPopView *popView;

@property(nonatomic,assign) BOOL firstLoad;
@property (nonatomic, strong) NSArray *typeArr;
@property (weak, nonatomic) IBOutlet UILabel *orderLabel;
@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
//蜘蛛图片
@property (nonatomic, strong) UIImageView *iconImageView;
//线条
@property (nonatomic, strong) UIView *lineView;

@end

@implementation ZZOrderVC
-(UIView *)lineView
{
    if (_lineView == nil) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor=blueColor;
         _lineView.frame=CGRectMake(newwidth-100+40, 64, 2, 40);
    }
    return _lineView;

}
-(UIImageView *)iconImageView
{
    if (_iconImageView == nil) {
        _iconImageView = [[UIImageView alloc] init];
        _iconImageView.image=[UIImage imageNamed:@"4"];
//        [[UIApplication sharedApplication].keyWindow addSubview:_iconImageView];
        _iconImageView.frame=CGRectMake(newwidth-100+1, 64, 80, 80);
    }
    return _iconImageView;

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.firstLoad = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.firstLoad = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
}
-(NSMutableArray *)mutaArr
{
    if (!_mutaArr) {
        _mutaArr = [NSMutableArray array];
    }
    return _mutaArr;
}

-(CcNoDataView *)noDataView
{
    if (_noDataView == nil) {
        _noDataView = [[CcNoDataView alloc] init];
        _noDataView.backgroundColor=[UIColor whiteColor];
    }
    return _noDataView;
    
}

-(ZZOrderHeaderView *)header
{
    if (!_header) {
        _header = [ZZOrderHeaderView zzOrderHeaderViewFromXib];
        _header.backgroundColor = [UIColor whiteColor];
    }
    return _header;
}

- (void)viewDidLoad {
    self.title = @"订单管理";
    
    [super viewDidLoad];
   
    [self getCurrentDate];

    [self createTableView];

    UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"ic_wxcb_01"] style:UIBarButtonItemStylePlain target:self action:@selector(popTheView)];
    
    self.navigationItem.rightBarButtonItem = btn;
    
    
    [self refreshAction];
    [self.tableView.mj_header beginRefreshing];
    
    [self.view addSubview:self.popView];
    self.startTime=@"";
    self.endTime=@"";
    self.PlateNumber=@"";
    self.Property=@"";
    [self showTimeOrNo];
    [self.view addSubview:self.iconImageView];
    [self.view addSubview:self.lineView];

}
//-(void)viewDidLayoutSubviews
//{
//    [super viewDidLayoutSubviews];
//    
//
//}
//蜘蛛的动画展示
-(void)showAnimag
{

    [UIView animateWithDuration:5 // 动画时长
                          delay:0.0 // 动画延迟
         usingSpringWithDamping:1.0 // 类似弹簧振动效果 0~1
          initialSpringVelocity:10.0 // 初始速度
                        options:UIViewAnimationOptionCurveEaseInOut // 动画过渡效果
                     animations:^{
                         self.lineView.mj_h=82;
                         self.iconImageView.mj_y=120;
                     } completion:^(BOOL finished) {
                         // 动画完成后执行
                            self.lineView.mj_h=80;
                         // code...
//                         [self.webView setAlpha:1];
                         
                     }];


}
//弹窗是否显示时间
-(void)showTimeOrNo
{
    if ([self.type isEqualToString:@"3"]) {
        self.popView.timeLabel.hidden=NO;
        self.popView.timeView.hidden=NO;
    }else
    {
        self.popView.timeLabel.hidden=YES;
        self.popView.timeView.hidden=YES;
    }
   


}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
       [self showAnimag];
    
    if (!self.firstLoad) {
        self.popView.frame = CGRectMake(0, -[UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        self.firstLoad = YES;
    }
    
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if (!_header) {
//        _header = [ZZOrderHeaderView zzOrderHeaderViewFromXib];
//        _header.frame =CGRectMake(0, newheight-70, newwidth, 70);
//        _header.backgroundColor = [UIColor lightGrayColor];
//    }
//    return _header;
//}

//-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
//{
//    if (!_header) {
//        _header = [ZZOrderHeaderView zzOrderHeaderViewFromXib];
//       // _header.frame =CGRectMake(0, newheight-70, newwidth, 70);
//        _header.backgroundColor = [UIColor whiteColor];
//    }
//    return _header;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

// 创建tableView
-(void)createTableView
{
    
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, newwidth, newheight-44-64) style:UITableViewStyleGrouped];
        _tableView.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.separatorStyle=0;
        [self.view addSubview:_tableView];
    }
}
-(void)settitleView
{
    UILabel *label=[[UILabel alloc] init];
    label.text=@"订单管理";
    label.textColor=[UIColor blackColor];
    [label sizeToFit];
    label.frame=CGRectMake(newwidth/2-label.frame.size.width/2, 20, label.frame.size.width, label.frame.size.height);
    self.navigationItem.titleView=label;
}
//刷新
-(void)reFreashwithType:(NSDictionary *)dic
{
    self.Property=dic[@"Name"];
    [self.tableView.mj_header beginRefreshing];

}
//查询数据
-(void)seletecdDataWithplatNum:(NSString *)platNum andStartTime:(NSString *)startTime andEndTime:(NSString *)endTime andDic:(NSDictionary *)dic
{
    self.PlateNumber=platNum;
    self.startTime=startTime;
    self.endTime=endTime;
      self.Property=dic[@"Name"];
    self.popView.dismissBlock();
    [self.tableView.mj_header beginRefreshing];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZZOrderHeaderViewCell *Cell = [ZZOrderHeaderViewCell cellWithTableVIew:tableView];
    Cell.model = _dataArr[indexPath.row];
    Cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return Cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

-(void)popDateMenu
{
    
    [self returnSixYearAndMonth];
    
    NSMutableArray *obj = [NSMutableArray array];
    
    for (NSInteger i = 0; i < _mutaArr.count; i++) {
        
        WBPopMenuModel * info = [WBPopMenuModel new];
        info.title = [self titles][i];
        [obj addObject:info];
    }
    
    NSLog(@"%@",obj);
    WEAKSELF
    [[WBPopMenuSingleton shareManager]showPopMenuSelecteWithFrame:120
                                                             item: obj
                                                           action:^(NSInteger index) {
                                                               NSLog(@"index:%ld",(long)index);
                                                     
                                                               [weakSelf refreshSelectActionWithTitle:_mutaArr[index]];
                                                   [weakSelf initDataWithDateTime:_mutaArr[index] andPageIndex:1];
                                                               
                                                               
                                                               
                                                           }];

}

-(void)popTheView
{
    [UIView animateWithDuration:0.3 animations:^{
        self.popView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        self.popView.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    }];
}

- (NSArray *) titles {
    DLog(@"%@",_mutaArr);
    
    return _mutaArr;
}


-(void)returnSixYearAndMonth
{
    // 获取当前秒
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeInterval time1970 = [now timeIntervalSince1970];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
//    NSUInteger numberOfDaysInMonth = range.length;
    NSUInteger numberOfDaysInMonth = 30;
      NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 10 ; i++) {
        
        // 格式化时间
        NSDate *dateTime = [NSDate dateWithTimeIntervalSince1970:time1970-(86400*numberOfDaysInMonth*i)];
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
        [dateFormat setDateFormat:@"yyyy年MM月"];
        [dateFormat stringFromDate:dateTime];
        
        NSLog(@"%@",dateTime);
        
        //得到近6月时间
        NSString *string = [NSString stringWithFormat:@"%@",dateTime];
         NSLog(@"%@",string);
        ZZTimeModel *model = [[ZZTimeModel alloc]init];
        model.year = [string substringToIndex:4];
        model.month = [string substringWithRange:NSMakeRange(5, 2)];
        NSString *timeStr = [NSString stringWithFormat:@"%@年%@月",model.year,model.month];
        NSLog(@"%@",timeStr);
        [arr addObject:timeStr];
        _mutaArr = arr;
    }
    
    
}
//查询类型
-(void)seletecdType
{   NSUserDefaults *loginDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary   *loginDict = [loginDefaults objectForKey:@"loginInfo"];

    [[ZZOrderViewModel shareViewModel] getOrderWithCompanyID:loginDict[@"CompanyID"] andcompanyfid:loginDict[@"CompanyFID"] andSuccess:^(NSDictionary *result) {
        NSLog(@"res=%@",result);
        NSString *resStr=result[@"resultJson"];
        self.typeArr=[WHJSON objectFormJsonString:resStr];
        self.popView.typeArr=self.typeArr;
        
        
        
        
    } andFailer:^{
        
    }];

}

-(void)initDataWithDateTime:(NSString *)dateTime andPageIndex:(NSInteger)pageIndex
{
    NSString *PageIndex = [NSString stringWithFormat:@"%ld",(long)pageIndex];
    NSUserDefaults *loginDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary   *loginDict = [loginDefaults objectForKey:@"loginInfo"];
    
    [[ZZOrderViewModel shareViewModel] getOrderWithCompanyID:loginDict[@"CompanyID"] andPageIndex:PageIndex andtype:self.type andStartTime:self.startTime andEndTime:self.endTime andPlateNumber:self.PlateNumber andRepairProperty:self.Property andSuccess:^(NSDictionary *result) {
        if (result) {
            
            [ZZOrderModel mj_setupObjectClassInArray:^NSDictionary *{
                return @{
                         @"rows" : @"ZZOrderContentModel",
                         };
            }];
            
            
            ZZOrderModel *fg = [ZZOrderModel mj_objectWithKeyValues:result[@"resultJson"]];
            NSDictionary *dic=[WHJSON objectFormJsonString:result[@"resultJson"]];
            [self showTheOrderAndMoneyWithDic:dic];
            
            self.total = [fg.total integerValue];
            
            
            if (!ceilf([fg.total floatValue] / 10.00)) {
                NSInteger x = 0;
                self.num = x;
            }else{
                NSInteger x = ceilf([fg.total floatValue] / 10.00);
                self.num = x;
            }
            
            
            if (self.index!=1) {
                if (self.index > self.num) {
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [_dataArr addObjectsFromArray:fg.rows];
                }
                [self.tableView.mj_footer endRefreshing];
            }

            else
            {
                _dataArr = fg.rows;
                
                [self.tableView.mj_header endRefreshing];
                
            }
            
            NSLog(@"%@",_dataArr);
            
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            
            
            [self.noDataView dataIsEmpty:_dataArr withView:self.tableView andNoDataView:self.noDataView andRect:CGRectMake(0, 0, newwidth, newheight-64) andBtnHiddne:YES];
        }

        
    } andFailer:^{
        [self.tableView.mj_header endRefreshing];
        [self.noDataView noNetwithView:self.tableView andNoDataView:self.noDataView andRect:CGRectMake(0, 0, newwidth, newheight) andBtnHiddne:NO];
        //点击重新加载的block
        WEAKSELF
        self.noDataView.myBlock=^{
            [weakSelf.tableView.mj_header beginRefreshing];
        };

        
    }];

}
//显示总金额和订单数
-(void)showTheOrderAndMoneyWithDic:(NSDictionary *)dic
{
    if (dic) {
        NSDictionary *sumDic=dic[@"sum"];
        if (sumDic) {
            UIColor *allColor=CXBColor(51, 51, 51);
            UIColor *markColor=[UIColor redColor];
            self.moneyLabel.text=[NSString stringWithFormat:@"¥%.2lf",[sumDic[@"SumMoney"] floatValue]];
            self.moneyLabel.textColor=markColor;
            self.orderLabel.text=[NSString stringWithFormat:@"%ld单",[sumDic[@"OrderNum"] integerValue]];
            self.orderLabel.textColor=markColor;
            NSMutableAttributedString *strAtt = [[NSMutableAttributedString alloc] initWithString:self.orderLabel.text];
           
            NSRange range=NSMakeRange(self.orderLabel.text.length-1, 1);
//            [strAtt addAttribute:NSForegroundColorAttributeName value:allColor range:range];
       
            [strAtt addAttribute:NSForegroundColorAttributeName value:allColor range:range];
            [strAtt addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue" size:16] range:range];
            self.orderLabel.attributedText = strAtt;
        }
        
        
    }
    


}

-(void)toShowSetting
{
   ZZSettingVC *vc = [[ZZSettingVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)getCurrentDate
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *nowdate = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
    comps = [calendar components:unitFlags fromDate:nowdate];
    
    NSLog(@"%ld年",(long)[comps year]);
    NSLog(@"%ld月",(long)[comps month]);
    NSLog(@"%ld日",(long)[comps day]);
    NSLog(@"%ld时",(long)[comps hour]);
    NSLog(@"%ld分",(long)[comps minute]);
    NSLog(@"%ld秒",(long)[comps second]);
    
    self.currentMonthStr = [NSString stringWithFormat:@"%ld年%ld月",(long)[comps year],(long)[comps month]];
}

- (void)refreshAction {
    // 下拉刷新
    weakSelf(weakSelf);
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataArr removeAllObjects];
        weakSelf.index = 1;

        weakSelf.header.MonthIncomeLabel.text = [NSString stringWithFormat:@"¥%@",[ZZUserModel shareViewModel].monthAllMoney];
        weakSelf.header.todayIncomeLabel.text = [NSString stringWithFormat:@"¥%@",[ZZUserModel shareViewModel].todayMoney];
        //[_tableView reloadData];
        [weakSelf initDataWithDateTime:weakSelf.currentMonthStr andPageIndex:weakSelf.index];
        [self seletecdType];
    }];
    
    // 上拉刷新
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.index = weakSelf.index + 1;
        [weakSelf initDataWithDateTime:weakSelf.currentMonthStr andPageIndex:weakSelf.index];
    }];
}


-(void)refreshSelectActionWithTitle:(NSString *)title  {
    // 下拉刷新
    weakSelf(weakSelf);
    self.tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataArr removeAllObjects];
        weakSelf.index = 1;
        [_tableView reloadData];
        [weakSelf initDataWithDateTime:title andPageIndex:weakSelf.index];
    }];
    
    // 上拉刷新
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.index = weakSelf.index + 1;
        [weakSelf initDataWithDateTime:weakSelf.currentMonthStr andPageIndex:weakSelf.index];
    }];
}

-(ZZOrderPopView *)popView
{
    if(!_popView){
        _popView = [[NSBundle mainBundle]loadNibNamed:NSStringFromClass([ZZOrderPopView class] ) owner:nil options:nil].lastObject;
        __weak typeof(_popView) weakPopView = _popView;
        _popView.delegate=self;
        [_popView setDismissBlock:^{
            weakPopView.backgroundColor = [UIColor clearColor];
            [UIView animateWithDuration:0.3 animations:^{
                weakPopView.frame = CGRectMake(0, -[UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
            }];
        }];
        
        _popView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    }
    return _popView;
}
@end
//wao
